package service;

import JDBC.DBUtils;
import com.google.gson.JsonObject;
import method.ItemCollect;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
/**
 * @author Gao Shiwei
 * user can cancel collection from here
 */
@WebServlet(name = "ItemDislike")
public class ItemDislike extends HttpServlet {
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setHeader("Access-Control-Allow-Origin", req.getHeader("Origin"));
        resp.setHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, If-Modified-Since");
        resp.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
        resp.setHeader("Access-Control-Max-Age", "3600");
        resp.addHeader("Access-Control-Allow-Credentials", "true");
        HttpSession session = req.getSession();
        String PhoneNumber = (String) session.getAttribute("PhoneNumber");
        String ItemID=req.getParameter("ItemID");
        ItemCollect[] Collect= DBUtils.QueryItemCollect("PhoneNumber",PhoneNumber);
        boolean answer=false;
        for(int i=0;i<Collect.length;i++){
            System.out.println(Collect[i].getItemID());
            if(ItemID.equals(Collect[i].getItemID())) {
                System.out.println("zzzzzzz");
                answer=true;
                break;
            }
        }
        if(answer==true){
            System.out.println("find");
            answer=DBUtils.deleteData("item_collect","ItemID",ItemID);
            JsonObject Container=new JsonObject();
            Container.addProperty("answer",answer);
            PrintWriter out = resp.getWriter();
            out.println(Container);
            out.flush();
            out.close();
        }else{
            System.out.println("not found");
            JsonObject Container=new JsonObject();
            Container.addProperty("answer",answer);
            PrintWriter out = resp.getWriter();
            out.println(Container);
            out.flush();
            out.close();
        }
    }
}
